package com.scujj.controller.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.scujj.controller.UserChatController;
import com.scujj.pojo.ChatRecords;
import com.scujj.pojo.Result;
import com.scujj.service.ChatRecordsService;
import com.scujj.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/chat")
@Api(tags = "聊天记录接口")
public class UserChatControllerImpl implements UserChatController {
    @Autowired
    private ChatRecordsService chatRecordsService;
    @Autowired
    private UserService userService;

    @Override
    @GetMapping("/getRecords")
    @ApiOperation("查找用户所有聊天记录")
    public Result findAllChat(@RequestParam("uid") Long uid, @RequestParam("guid") Long guid) {
        if (uid == null || guid == null) {
            return Result.error("参数错误");
        }
        QueryWrapper<ChatRecords> wrapper = new QueryWrapper<>();
        wrapper.eq("suid", uid).eq("guid", guid).or().eq("guid", uid).eq("suid", guid);
        wrapper.orderByAsc("publishTime");
        List<ChatRecords> chatRecordsList = chatRecordsService.list(wrapper);
        chatRecordsList.forEach(chatRecords -> {
            chatRecords.setSuser(userService.getById(chatRecords.getSuid()).setPassword(null));
            chatRecords.setGuser(userService.getById(chatRecords.getGuid()).setPassword(null));
        });
        return Result.success(chatRecordsList);
    }

    @Override
    @DeleteMapping("/deleteRecords")
    @ApiOperation("批量删除聊天记录")
    public Result deleteChatByIdList(@RequestBody List<Long> idList) {
        if (chatRecordsService.removeByIds(idList)) {
            return Result.success();
        } else {
            return Result.error("网络错误");
        }
    }

    @Override
    @GetMapping("/getChatList")
    @ApiOperation("获取聊天列表")
    public Result findAllChatList(@RequestParam("id") Long uid) {
        if (uid == null) {
            return Result.error("参数错误");
        }
        List<ChatRecords> chatRecordsList = chatRecordsService.getChatList(uid);
        return Result.success(chatRecordsList);
    }
}
